package com.etrans.web.gps.business.base.controller;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.javassist.util.proxy.ProxyFactory.UniqueName;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.base.domain.Unit;
import com.etrans.web.gps.business.base.service.UnitService;
import com.etrans.web.gps.business.system.domain.SysUser;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.common.page.ResultContans;
import com.etrans.web.gps.util.StringUtils;
import com.etrans.web.gps.util.TreeCommon;
import com.etrans.web.gps.util.grid.FlexiGridUtil;

/**
 * 企业collector类
 * 
 * @author liurong
 *
 */
@Controller
@RequestMapping("/base/unit/*")
public class UnitController extends BaseController {
	private final static Logger log = LoggerFactory.getLogger(UnitController.class);
	@Autowired
	private UnitService unitService;

	@RequestMapping(value = "queryFullUnitTree.html")
	@ResponseBody
	public List queryFullUnitTree(@RequestParam  String name) {
		List<Unit> rows = null;

		List<Map<String, Object>> unitTree = null;
		try {
			// 参数赋值
			HashMap<String, Object> paramsMap = new HashMap<String, Object>();
			// SysUser user = getSysUser();
			// 是否企业管理员
		//	paramsMap.putAll(getUnitlevelParam(request));
			// 先查出所有的企业信息，按照fullID排序
			List<HashMap<String, Object>> listTreeList = unitService.queryFullUnitTree( paramsMap);
			// 获取顶级企业的长度
			int FirUnitlevel = 0;
			//
			if (listTreeList.size() > 0) {
				FirUnitlevel = listTreeList.get(0).get("FullID").toString().length();
			}
			// 创建树
			unitTree = TreeCommon.createTree(listTreeList, FirUnitlevel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return unitTree;

	}
	
	@RequestMapping(value = "queryFullUnitTreeByUnitId.html")
	@ResponseBody
	public List queryFullUnitTreeByUnitId(@RequestParam  String name) {
		List<Unit> rows = null;
		SysUser user = getSysUser();
		
		List<Map<String, Object>> unitTree = null;
		try {
			// 参数赋值
			HashMap<String, Object> paramsMap = new HashMap<String, Object>();
		
			// 先查出所有的企业信息，按照fullID排序
			List<HashMap<String, Object>> listTreeList = unitService.queryFullUnitTreeByUnitId( paramsMap);
			// 获取顶级企业的长度
			int FirUnitlevel = 0;
			//
			if (listTreeList.size() > 0) {
				FirUnitlevel = listTreeList.get(0).get("FullID").toString().length();
			}
			// 创建树
			unitTree = TreeCommon.createTree(listTreeList, FirUnitlevel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return unitTree;

	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "queryFullUnitTreeByAuth.html")
	@ResponseBody
	public List queryFullUnitTreeByAuth() {
		List<Unit> rows = null;

		List<Map<String, Object>> unitTree = null;
		try {
			// 参数赋值
			HashMap<String, Object> paramsMap = new HashMap<String, Object>();
			// 先查出所有的企业信息，按照fullID排序
			List<HashMap<String, Object>> listTreeList = unitService.queryFullUnitTreeByAuth( paramsMap);
			// 获取顶级企业的长度
			int FirUnitlevel = 0;
			//
			if (listTreeList.size() > 0) {
				FirUnitlevel = listTreeList.get(0).get("FullID").toString().length();
			}
			// 创建树
			unitTree = TreeCommon.createTree(listTreeList, FirUnitlevel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return unitTree;

	}

	// 查询所有单位
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "loadAllUnits.html")
	@ResponseBody
	public PageVo loadAllUnits(@RequestParam  String paramsGrid) {
		PageVo page = new PageVo();
		try {
			Map<String, Object> paramMap = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
			/*List<SubPlatform> subPlatForm = (List<SubPlatform>) getSession().getAttribute(Constant.USER_OP_SUB);
			for(SubPlatform sub:subPlatForm){
				if(dbKey.equals(sub.getDb_pool())&&sub.getRole_work_unit_id()!=-1){
					Unit u =unitService.queryUnitById( sub.getRole_work_unit_id());
					if(u!=null&&u.getFullId()!=null){
						paramMap.put("authWorkUnitFullId", u.getFullId());
					}
				}
			};*/
			List rows = unitService.queryAllUnitList( paramMap);
			page.setRows(rows);
			page.setPage((int) paramMap.get("page"));
			page.setTotal(unitService.queryAllUnitListCount( paramMap));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return page;

	}

	// 查询所有单位
	@RequestMapping(value = "loadSubAllUnits.html")
	@ResponseBody
	public List loadSubAllUnits(@RequestParam  HttpServletRequest req, HttpServletResponse res) {

		try {
			HashMap<String, Object> param = getReqParameters();
		//	param.putAll(getUnitlevelParam(request));
			HashMap<String, Object> temp =new HashMap<>();
			temp.put("ID", "");
			temp.put("Name","请选择企业");
		
			List<HashMap<String, Object>> list = unitService.querySubFullUnit( param);
			//list.add(temp);
			list.add(0, temp);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	@RequestMapping(value = "queryFullUnitTreeCombo.html")
	@ResponseBody
	public List queryFullUnitTreeCombo(@RequestParam  String name, boolean combo, boolean isParent) {
		List<HashMap<String, Object>> unitTree = new ArrayList<HashMap<String, Object>>();
		List<Unit> rows = null;
		HashMap<String, Object> root = new HashMap<>();
		try {
			// 参数赋值
			HashMap<String, Object> paramsMap = new HashMap<String, Object>();
			List<HashMap<String, Object>> listTreeList = unitService.queryFullUnitTree( paramsMap);

			// 构建树
			HashMap<String, Object> perhashMaptree;
			for (HashMap<String, Object> hashMap : listTreeList) {
				perhashMaptree = new HashMap<String, Object>();
				perhashMaptree.put("id", hashMap.get("ID"));
				perhashMaptree.put("name", hashMap.get("Name"));
				perhashMaptree.put("pid", hashMap.get("ParentID"));
				unitTree.add(perhashMaptree);
			}

			SetFullIDZero(unitTree);
			// 如果父节点没有存在，则父节点ID设置为0
			// 创建树
			// 创建父节点"全部企业"

			perhashMaptree = new HashMap<String, Object>();
			perhashMaptree.put("id", 0);
			perhashMaptree.put("name", "全部企业");
			perhashMaptree.put("pid", -1);
			unitTree.add(perhashMaptree);

		} catch (Exception e) {
			// logger.error("", e);
			e.printStackTrace();
		}
		// ajaxResultJson(response,combo ? unitTree : unitTree);
		return unitTree;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "queryFullUnitTreeComboByAuth.html")
	@ResponseBody
	public List queryFullUnitTreeComboByAuth(@RequestParam  String name, boolean combo, boolean isParent) {
		List<HashMap<String, Object>> unitTree = new ArrayList<HashMap<String, Object>>();
		List<Unit> rows = null;
		HashMap<String, Object> root = new HashMap<>();
		try {
			// 参数赋值
			HashMap<String, Object> paramsMap = new HashMap<String, Object>();
			/*List<SubPlatform> subPlatForm = (List<SubPlatform>) getSession().getAttribute(Constant.USER_OP_SUB);
			for(SubPlatform sub:subPlatForm){
				if(dbKey.equals(sub.getDb_pool())&&sub.getRole_work_unit_id()!=-1){
					Unit u =unitService.queryUnitById( sub.getRole_work_unit_id());
					if(u!=null&&u.getFullId()!=null){
						paramsMap.put("authWorkUnitFullId", u.getFullId());
					}
				}
			};*/
			List<HashMap<String, Object>> listTreeList = unitService.queryFullUnitTreeByAuth( paramsMap);

			// 构建树
			HashMap<String, Object> perhashMaptree;
			for (HashMap<String, Object> hashMap : listTreeList) {
				perhashMaptree = new HashMap<String, Object>();
				perhashMaptree.put("id", hashMap.get("ID"));
				perhashMaptree.put("name", hashMap.get("Name"));
				perhashMaptree.put("pid", hashMap.get("ParentID"));
				unitTree.add(perhashMaptree);
			}

			SetFullIDZero(unitTree);
			// 如果父节点没有存在，则父节点ID设置为0
			// 创建树
			// 创建父节点"全部企业"

			perhashMaptree = new HashMap<String, Object>();
			perhashMaptree.put("id", 0);
			perhashMaptree.put("name", "全部企业");
			perhashMaptree.put("pid", -1);
			unitTree.add(perhashMaptree);

		} catch (Exception e) {
			// logger.error("", e);
			e.printStackTrace();
		}
		// ajaxResultJson(response,combo ? unitTree : unitTree);
		return unitTree;
	}
	
	private void SetFullIDZero(List<HashMap<String, Object>> unitList) {
		String unitIDString = "";
		String pid = "";
		for (HashMap<String, Object> hashMap : unitList) {
			unitIDString = unitIDString + String.format(",%s", hashMap.get("id"));
		}
		if (unitIDString.length() > 0) {
			unitIDString = String.format("%s,", unitIDString);
		}
		for (HashMap<String, Object> hashMap : unitList) {
			if (!hashMap.containsKey("pid")) {
				hashMap.put("pid", 0);
			} else {
				if (hashMap.get("pid") == null) {
					hashMap.put("pid", 0);
				} else {
					pid = String.format(",%s,", hashMap.get("pid").toString());
					// 如果没有存在，设置父ID为0
					if (unitIDString.indexOf(pid) == -1) {
						hashMap.put("pid", 0);
					}
				}

			}

		}

	}

	// 查询所有行业类型
	@RequestMapping(value = "loadAllTradeKinds.html")
	@ResponseBody
	public List loadAllTradeKinds(@RequestParam String dbKey) {
		List rows = new ArrayList();
		try {
			rows = unitService.queryAllTradeKinds(dbKey);

		} catch (Exception e) {
			// logger.error("", e);
			e.printStackTrace();
		}
		return rows;
	}

	// 查询所有机构类型
	@RequestMapping(value = "loadAllOrganzationKinds.html")
	@ResponseBody
	public List loadAllOrganzationKinds(@RequestParam String dbKey) {
		List rows = new ArrayList();
		try {
			rows = unitService.loadAllOrganzationKinds(dbKey);

		} catch (Exception e) {
			// logger.error("", e);
			e.printStackTrace();
		}
		return rows;
	}

	/**
	 * 所属区域
	 * 
	 * @param name
	 */
	@RequestMapping(value = "loadAreaTreesExtend.html")
	@ResponseBody
	public List loadAreaTreesExtend() {
		List<Map<String, Object>> unitTreeList = null;
		try {
			// 参数赋值
			HashMap<String, Object> paramsMap = new HashMap<String, Object>();
		//	paramsMap.put("name", name);

			// 先查出所有的区域信息，按照fullID排序
			List<HashMap<String, Object>> listTreeList = unitService.queryUnitTreeExtend( paramsMap);
			// 创建树
			unitTreeList = TreeCommon.createTree(listTreeList, 8);

		} catch (Exception e) {
			// logger.error("", e);
			e.printStackTrace();
		}
		return unitTreeList;
	}

	@RequestMapping(value = "initUnit.html")
	@ResponseBody
	public ModelAndView initUnit(@RequestParam  Integer parentUnitID) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("action", "insert");
		mav.addObject("parentId", parentUnitID);
		mav.addObject("unit", new Unit());
		mav.setViewName("views/base/unit/addUnitForm");
		return mav;
	}

	@RequestMapping(value = "initUpdateUnit.html")
	@ResponseBody
	public ModelAndView initUpdateUnit(@RequestParam  Integer unitId) {
		ModelAndView mav = new ModelAndView();
		Unit unit = unitService.queryUnitById( unitId);
		mav.addObject("action", "update");
		mav.addObject("unitId", "unitId");
		mav.addObject("unit", unit);
		mav.setViewName("views/base/unit/addUnitForm");
		return mav;
	}

	@RequestMapping(value = "updateUnit.html")
	@ResponseBody
	public Unit updateUnit(@RequestParam  Integer unitId) {
		Unit unit = new Unit();
		try {
			// 查找相应的司机
			unit = unitService.queryUnitById( unitId);
		} catch (Exception e) {
			// logger.error("", e);
			e.printStackTrace();
		}

		return unit;
	}

	@RequestMapping(value = "saveUnit.html")
	@ResponseBody
	public Map saveUnit(@RequestParam  String action, Unit unit) {
		Map result = new HashMap();
		try {
			// 首先查看是否有重复的企业名称，保证企业名称唯一
			HashMap<String, Object> parms = new HashMap<String, Object>();
			parms.put("Name", unit.getName());
			parms.put("ParentID", unit.getParentId());
			if ("update".equals(action)) {
				parms.put("ID", unit.getId());
			}
			int Count = unitService.queryCountByUnitName( parms);
			if (Count == 0) {
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				if ("insert".equals(action)) {
					// 创建时间
					unit.setCreateDateTime(dateFormat.format(new Date()));
					// 修改时间
					unit.setModifyDateTime(dateFormat.format(new Date()));
					// 默认不删除状态
					unit.setIsDeleted(0);
					// 设置全名
					unit.setFullName(unit.getName());
					// 直接保存
					unitService.saveUnit( unit);
				}
				if ("update".equals(action)) {
					// 修改时间
					unit.setModifyDateTime(dateFormat.format(new Date()));
					// 默认不删除状态
					unit.setIsDeleted(0);
					unitService.updateUnit( unit);
				}
				result.put("code", Constant.RETURN_OK_CODE);
				result.put("msg", unit.getId().toString());
			} else {
				result.put("code", Constant.RETURN_Repent_CODE);
			}
		} catch (Exception e) {
			// logger.error("", e);
			e.printStackTrace();
			result.put("code", Constant.RETURN_ERROR_CODE);
			result.put("msg", "保存失败!");
		}
		return result;
	}

	@RequestMapping(value = "importWorkUnit.html")
	@ResponseBody
	public Map importWorkUnit(@RequestParam  HttpServletRequest request, HttpServletResponse response,
			MultipartHttpServletRequest multipartRequest, String fileUploadId) {
		Map result = new HashMap();
		SysUser user = getSysUser();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			MultipartFile file = multipartRequest.getFile(fileUploadId); // 根据前台的name名称得到上传的文件
			InputStream iso = file.getInputStream();
			HSSFWorkbook wb = new HSSFWorkbook(iso);
			HSSFSheet sheet = wb.getSheetAt(0);
			List<Unit> cmpList = new ArrayList<Unit>();
			StringBuilder errorList = new StringBuilder();
			// 所有行业类型
			HashMap<String, Integer> vehicleTrade = getVehicleTrade();
			HashMap<String, Integer> organizationkind = getOrganizationkind();
			for (int i = 1; i <= sheet.getLastRowNum(); i++) {// 从第二行开始
				Unit unit = new Unit();
				HSSFRow row = sheet.getRow(i);
				if (null == row) {
					continue;
				}
				String name = getCellValue(row.getCell(0));// cell0.getStringCellValue();
				String shortname = getCellValue(row.getCell(1));// cell1.getStringCellValue();
				String code = getCellValue(row.getCell(2));// cell2.getStringCellValue();
				String areaid = getCellValue(row.getCell(3));// cell3.getStringCellValue();
				String organizationkindid = getCellValue(row.getCell(4));// cell4.getStringCellValue();
				String tradekindid = getCellValue(row.getCell(5));// cell5.getStringCellValue();
				String upunitname = getCellValue(row.getCell(6));// cell6.getStringCellValue();
				log.info(
						"第{}行数据name={},shortname={},code={},areaid={},organizationkindid={},tradekindid={},upunitname={}",
						(i + 1), name, shortname, code, areaid, organizationkindid, tradekindid, upunitname);
				if (StringUtils.isNULL(name) || StringUtils.isNULL(upunitname)) {
					log.info("第" + (i + 1) + "行,企业名称或上级企业名称为空..........name:{},upunitname:{}.", name, upunitname);
					errorList.append("第" + (i + 1) + "行,企业名称或上级企业名称为空,");
					continue;
				}
				HashMap<String, Object> params = new HashMap<String, Object>();
				params.put("name", name);
				Unit tmp1 = unitService.queryUnitByName( params);
				if (tmp1 != null) {
					log.info("第" + (i + 1) + "行,企业已存在............", name);
					errorList.append("第" + (i + 1) + "行,企业已存在,");
					continue;
				}
				params.put("name", upunitname);
				Unit tmp = unitService.queryUnitByName( params);
				if (tmp == null) {
					log.info("第" + (i + 1) + "行,上级企业不存在............", upunitname);
					errorList.append("第" + (i + 1) + "行,上级企业不存在,");
					continue;
				}

				unit.setParentId(tmp.getId());

				unit.setCreateUserId(user.getId());
				unit.setName(name);
				unit.setFullName(name);
				unit.setShortName(shortname);
				unit.setCode(code);
				unit.setCreateDateTime(dateFormat.format(new Date()));
				unit.setModifyDateTime(dateFormat.format(new Date()));
				unit.setIsDeleted(0);
				unit.setAreaId(Integer.parseInt(areaid));

				unit.setOrganizationKindId(organizationkind.get(organizationkindid));
				unit.setTradeKindId(vehicleTrade.get(tradekindid));

				unitService.saveUnit( unit);

				cmpList.add(unit);
			}
			log.info("共导入企业数: " + cmpList.size());
			result.put("code", Constant.RETURN_OK_CODE);
			result.put("data", errorList.toString());
		} catch (Exception e) {
			// logger.error("", e);
			result.put("code", Constant.RETURN_ERROR_CODE);
			result.put("data", "导入失败!");
			e.printStackTrace();
		}
		return result;
	}

	private HashMap<String, Integer> getVehicleTrade() {
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		map.put("班车客运", 1);
		map.put("包车客运", 2);
		map.put("定线旅游", 3);
		map.put("道路普通货物运输", 4);
		map.put("货物专用运输", 5);
		map.put("大型物件运输", 6);
		map.put("营运性危险货物运输", 7);
		map.put("非经营危险货物运输", 8);
		map.put("客运出租运输", 9);
		map.put("货运出租运输", 10);
		map.put("公司用车", 11);
		map.put("部队用车", 12);
		map.put("校巴", 13);
		return map;
	}

	private HashMap<String, Integer> getOrganizationkind() {
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		map.put("政府机构", 1);
		map.put("企业机构", 2);
		return map;
	}

	public String getCellValue(HSSFCell cell) {
		String result = new String();
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_NUMERIC:// 数字类型
			if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = cell.getDateCellValue();
				result = sdf.format(date);
			} else {
				double value = cell.getNumericCellValue();
				CellStyle style = cell.getCellStyle();
				DecimalFormat format = new DecimalFormat();
				String temp = style.getDataFormatString();
				// 单元格设置成常规
				if (temp.equals("General")) {
					format.applyPattern("#");
				}
				result = format.format(value);
			}
			break;
		case HSSFCell.CELL_TYPE_STRING:// String类型
			result = cell.getRichStringCellValue().toString();
			break;
		case HSSFCell.CELL_TYPE_BLANK:
			result = "";
			break;
		default:
			result = "";
			break;
		}
		return result;
	}

	// 删除单位信息
	@RequestMapping(value = "delUnit.html")
	@ResponseBody
	public Map<String,Object> delUnit(@RequestParam  String UnitIds) {
		Map<String,Object> result = new HashMap<>();
		try {
			Integer vehiclecount = 0;
			Integer childUnitCount = 0;
			boolean ifDeleted = true;
			if (UnitIds != null && !"".equals(UnitIds)) {
				String[] ArrayUnitId = UnitIds.split(",");
				for (String perID : ArrayUnitId) {
					vehiclecount = unitService.queryCountByUnitID( Integer.parseInt(perID));
					if (vehiclecount > 0) {
						result.put("code", ResultContans.RETURN_REPENT_CODE.getCode());
						ifDeleted = false;
					}
					childUnitCount = unitService.queryChildUnitCountByUnitID(Integer.parseInt(perID));
					if (childUnitCount > 0) {
						result.put("code", ResultContans.RETURN_REPENT_CODE.getCode());
						ifDeleted = false;
					}
				}
				// 如果没存在车辆或者没有子企业，则可以继续删除操作
				if (ifDeleted) {
					for (String perID : ArrayUnitId) {
						unitService.deleteUnitByID( Integer.parseInt(perID));
						result.put("code", Constant.RETURN_OK_CODE);
					}
				}
			}
		} catch (Exception e) {
			// logger.error("", e);
			e.printStackTrace();
			result.put("code", Constant.RETURN_ERROR_CODE);
			result.put("msg", "删除失败!");
		}
		return result;
	}

	@RequestMapping(value = "changeParentUnit.html")
	@ResponseBody
	public Map changeParentUnit(@RequestParam  Integer UnitId, Integer txtParentId) {
		Map result = new HashMap();
		try {
			Unit unit = unitService.queryUnitById( UnitId);

			unit.setParentId(txtParentId);
			unitService.changeParentUnit( unit);
			result.put("code", Constant.RETURN_OK_CODE);
		} catch (Exception e) {
			// logger.error("", e);
			e.printStackTrace();
			result.put("code", Constant.RETURN_ERROR_CODE);
			result.put("msg", "保存失败!");
		}
		return result;
	}

	/**
	 * 导出企业信息
	 * 
	 * @param response
	 * @param paramsGrid
	 * @param StartPage
	 * @param EndPage
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "exportUnits.html")
	public void exportUnits(@RequestParam  HttpServletRequest request, HttpServletResponse response,
			String paramsGrid, String colModel, String title, String StartPage, String EndPage, String pagesize) {
		Map<String, Object> paramMap = getReqParameters();
		List<String> colModelList = JSON.parseObject(colModel, List.class);
		/*List<SubPlatform> subPlatForm = (List<SubPlatform>) getSession().getAttribute(Constant.USER_OP_SUB);
		for(SubPlatform sub:subPlatForm){
			if(paramMap.get("unitId")==null&&dbKey.equals(sub.getDb_pool())&&sub.getRole_work_unit_id()!=-1){
				Unit u =unitService.queryUnitById( sub.getRole_work_unit_id());
				if(u!=null&&u.getFullId()!=null){
					paramMap.put("authWorkUnitFullId", u.getFullId());
				}
			}
		};*/
		List<Unit> list = unitService.queryUnitExportList(paramMap);
		List<HashMap<String, String>> rows = new ArrayList<HashMap<String, String>>();

		int start = Integer.valueOf(Integer.valueOf(StartPage) - 1) * Integer.valueOf(pagesize);
		int end = Integer.valueOf(EndPage) * Integer.valueOf(pagesize);
		if (end > (list.size() - 1)) {
			end = list.size();
		}
		for (int i = start; i < end; i++) {
			Unit obj = (Unit) list.get(i);

			HashMap<String, String> map = new HashMap<String, String>();
			map.put("name", obj.getName() == null ? "" : obj.getName());
			map.put("shortName", obj.getShortName() == null ? "" : obj.getShortName());
			map.put("linkMan", obj.getLinkMan() == null ? "" : obj.getLinkMan());
			map.put("phoneNo", obj.getPhoneNo() == null ? "" : obj.getPhoneNo());
			map.put("backupPhoneNo", obj.getBackupPhoneNo() == null ? "" : obj.getBackupPhoneNo());
			map.put("address", obj.getAddress() == null ? "" : obj.getAddress());
			map.put("postCode", obj.getPostCode() == null ? "" : obj.getPostCode());
			map.put("regAddress", obj.getRegAddress() == null ? "" : obj.getRegAddress());
			rows.add(map);
		}
		int index = -1;
		List rowsList = new ArrayList<>();
		rowsList.add(rows);
		exportExl(request, response, title, removeHeadName(colModelList, index, -1), rowsList, null);
	}

	/**
	 * 用于查找当前用户代维企业所有的下级企业
	 * 
	 * @author grc
	 * 
	 */

	@RequestMapping(value = "queryAllUnit.html")
	@ResponseBody
	public Map<String, Object> queryAllUnit(@RequestParam  String name) {
		Map<String, Object> result = new HashMap<>();
		result.put("code", -1);
		try {
			// 参数赋值
			HashMap<String, Object> paramsMap = new HashMap<String, Object>();
			List<HashMap<String, Object>> Unitlist = null;
			
			Unitlist = unitService.querySubFullUnit( paramsMap);
			result.put("code", 0);
			result.put("UnitList", Unitlist);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("msg", "接口错误！");
		}
		return result;

	}

}
